package org.example;

import com.sun.jna.platform.win32.Kernel32;
import com.sun.jna.platform.win32.User32;
import com.sun.jna.platform.win32.WinDef;
import com.sun.jna.platform.win32.WinUser;

import java.util.Date;

public class MouseHook implements Runnable{
    public static boolean nomove = false;

    public GlobalKeyListenerExample globalKeyListenerExample;

    @Override
    public void run() {
        setHookOn();
    }

    private WinUser.HHOOK hhk;

    private WinUser.LowLevelKeyboardProc mouseProc = new WinUser.LowLevelKeyboardProc() {

        @Override
        public WinDef.LRESULT callback(int nCode, WinDef.WPARAM wParam, WinUser.KBDLLHOOKSTRUCT event) {
            if (nCode >= 0) {
                // 拦截鼠标移动消息
//                if (nomove && wParam.intValue() == 512) {
                    // 返回非零值表示已处理该消息，阻止传递
//                    return new WinDef.LRESULT(1);
//                }

                if (wParam.intValue() == 513) {
//                    System.out.println("click");
//                    try {
//                        GlobalKeyListenerExample.robot.keyPress(KeyEvent.VK_P);
//                        Thread.sleep(301);
//                        GlobalKeyListenerExample.robot.keyRelease(KeyEvent.VK_P);pnpn
//                    } catch (InterruptedException e) {
//                        throw new RuntimeException(e);
//                    }
//                    GlobalKeyListenerExample.stop();
                }

                if (wParam.intValue() == 514) {
//                    GlobalKeyListenerExample.unstop();
                }

                if(wParam.intValue() == 516) {
                    GlobalKeyListenerExample.lasthuachan = System.currentTimeMillis();
//                    GlobalKeyListenerExample.robot.keyRelease();
                }
            }
            return User32.INSTANCE.CallNextHookEx(hhk, nCode, wParam, null);
        }
    };


    // 安装钩子
    public void setHookOn() {
        WinDef.HMODULE hMod = Kernel32.INSTANCE.GetModuleHandle(null);
        hhk = User32.INSTANCE.SetWindowsHookEx(User32.WH_MOUSE_LL, mouseProc, hMod, 0);
        int result;
        WinUser.MSG msg = new WinUser.MSG();
        while ((result = User32.INSTANCE.GetMessage(msg, null, 0, 0)) != 0) {
            if (result == -1) {
                setHookOff();
                break;
            } else {
                User32.INSTANCE.TranslateMessage(msg);
                User32.INSTANCE.DispatchMessage(msg);
            }
        }
    }

    // 移除钩子并退出
    public void setHookOff() {
        User32.INSTANCE.UnhookWindowsHookEx(hhk);
        System.exit(0);
    }

}
